<template>
	<view class="container">
		<!-- 表单主体 -->
		<uni-forms ref="form" :modelValue="formData" :rules="rules">
			<!-- 积分类型选择 -->
			<uni-forms-item label="积分类型" name="type">
				<uni-data-checkbox :localdata="types" v-model="formData.type" mode="button" />
			</uni-forms-item>

			<!-- 分值输入 -->
			<uni-forms-item label="积分分值" name="score">
				<uni-number-box v-model="formData.score" :min="0" :max="9999" :step="10" :value="0" />
			</uni-forms-item>
			<uni-forms-item label="姓名" name="description">
				<uni-easyinput type="text" v-model="formData.name" placeholder="请输入姓名" :maxlength="200" autoHeight />
			</uni-forms-item>
			<!-- 日期 -->
			<uni-forms-item>
				<view class="example-body">
					<uni-datetime-picker type="date" :clear-icon="false" v-model="formData.selectDate"
						@maskClick="maskClick" />
				</view>
			</uni-forms-item>
			<!-- 描述说明 -->
			<uni-forms-item label="说明描述" name="description">
				<uni-easyinput type="textarea" v-model="formData.description" placeholder="请输入详细说明（最多200字）"
					:maxlength="200" autoHeight />
			</uni-forms-item>

			<!-- 文件上传组件 -->
			<uni-forms-item label="佐证材料">
				<uni-file-picker v-model="fileList" limit="5" fileMediatype="all" :image-styles="imageStyles"
					@select="selectFile" @delete="deleteFile" />
				<text style="font-size: 12px; color: red;">单个大小不超过 5MB \n
					格式为 doc/xls/ppt/pdf 的文件</text>
			</uni-forms-item>
		</uni-forms>
		<button class="submit-btn" @click="submit">提交审核</button>
		<view class="score-info">
			<view class="info-title">积分说明</view>
			<view class="info-content">
				<view class="info-item">1. 积分类型说明：项目积分用于团队合作项目奖励，培训积分针对参与专业培训获取，活动积分面向各类线下活动参与人员。</view>
				<view class="info-item">2. 分值规则：项目积分：工资1块=1积分，活动积分：参加一次沙龙活动可获得500积分。</view>
				<view class="info-item">3. 佐证材料：需上传与申报内容相关的证明文件（如项目报告、培训证书、活动签到表等），文件格式限doc/xls/ppt/pdf。</view>
				<view class="info-item">4. 审核周期：提交后3个工作日内完成审核，可在"积分记录"页面查看审核状态。</view>
			</view>
		</view>
		<!-- 提交按钮 -->

	</view>
</template>
<script setup>
	import {
		ref,
		reactive
	} from 'vue'
	import {
		onReady
	} from '@dcloudio/uni-app'
	import {
		http
	} from '../../../utils/requestUtil';

	// 表单数据模型（参考网页5的数据结构设计）
	const formData = reactive({
		type: 'project', // 默认项目积分
		name: '',
		score: 0,
		description: '',
		tempFile: [],
		files: '',
		selectDate: ''
	})

	// 文件列表管理（基于网页6的上传逻辑优化）
	const fileList = ref([])
	const imageStyles = {
		height: 160,
		width: 160,
		border: {
			color: '#eee',
			width: 2,
			style: 'dashed'
		}
	}

	// 积分类型选项（参考网页1的分类）
	const types = [{
			value: 'project',
			text: '项目积分'
		},
		{
			value: 'training',
			text: '培训积分'
		},
		{
			value: 'activity',
			text: '活动积分'
		}
	]

	// 验证规则（融合网页5的数据校验要求）
	const rules = {
		type: {
			rules: [{
				required: true,
				errorMessage: '请选择积分类型'
			}]
		},
		score: {
			rules: [{
					required: true,
					errorMessage: '请输入分值'
				},
				{
					format: 'number',
					errorMessage: '必须为有效数字'
				}
			]
		},
		description: {
			rules: [{
					required: true,
					errorMessage: '请输入说明'
				},
				{
					validateFunction: (rule, value) => value.length <= 200,
					errorMessage: '最多200字'
				}
			]
		}
	}
	const maskClick = (e) => {
		console.log(e)
	}
	// 文件操作（优化网页6的上传逻辑）
	const selectFile = async (files) => {
		console.log(files.tempFilePaths)
		// for(let i=0;i<files.tempFilePaths.length;i++)
		// const files = await Promise.all(e.tempFilePaths.map(uploadFile))
		formData.tempFile = [...formData.tempFile, files.tempFilePaths]
		// console.log(formData.tempFile)
	}


	const deleteFile = (e) => {
		formData.tempFile = formData.files.filter(f => f.url !== e.tempFilePath)
	}

	const uploadFile = async () => {
	
		for (let i = 0; i < formData.tempFile.length; i++) {
			for (let j = 0; j < formData.tempFile[i].length; j++) {
				const res = await http.upload('/common/upload', formData.tempFile[i][j])
				if (formData.files == '') {
					formData.files = res.fileName
				} else {
					formData.files = formData.files + ',' + res.fileName
				}

				console.log(res)
				// console.log("fenge")
				// console.log(formData.files)
			}

		}


		// return new Promise((resolve) => {
		// 	uni.uploadFile({
		// 		url: '/api/upload',
		// 		filePath: path,
		// 		name: 'file',
		// 		success: (res) => {
		// 			resolve(JSON.parse(res.data))
		// 		}
		// 	})
		// })
	}

	// 表单提交（参考网页1的API调用规范）
const submit = async () => {
  const tempId = 'nOBpWMAyW_l91hC1YmG_9Bme8zgEYBvEl8d7e0Con7w'
  if (!formData.description) {
    uni.showToast({
      title: '请输入描述',
      icon: 'error'
    })
    return
  }
  
  try {
    await uploadFile()
    const a = await http.post('/bole/application', formData)
    
    uni.showToast({
      title: '提交成功',
      icon: 'success'
    })
    
    // 提交成功后，显示模态框让用户选择是否订阅
    uni.showModal({
      title: '订阅通知',
      content: '是否订阅审核结果通知？',
      success: (modalRes) => {
        if (modalRes.confirm) {
          // 用户点击确定，才调用订阅消息API
          requestSubscribeMessage(tempId)
        } else {
          // 用户取消订阅
          uni.$emit('refreshData', { refresh: true })
          setTimeout(() => {
            uni.navigateBack()
          }, 1000)
        }
      }
    })
    
  } catch (err) {
    uni.showToast({
      title: err || '请添加描述',
      icon: 'none'
    })
  }
}

// 单独封装订阅消息请求函数
const requestSubscribeMessage = (tempId) => {
  uni.requestSubscribeMessage({
    tmplIds: [tempId],
    success: (res) => {
      if (res[tempId] === 'accept') {
        uni.showToast({
          title: '订阅审核结果成功',
          icon: 'success'
        });
        uni.login({
          success: (loginRes) => {
            if (loginRes.code) {
              http.post("/bole/agreeSubscribe", {
                code: loginRes.code,
              })
            }
          },
        })
      } else {
        uni.showToast({
          title: '已拒绝订阅，审核结果将不会通知',
          icon: 'none',
          duration: 3000
        });
      }
      uni.$emit('refreshData', { refresh: true });
      setTimeout(() => {
        uni.navigateBack()
      }, 1000)
    },
    fail: (err) => {
      console.error('订阅请求失败：', err);
      uni.showToast({
        title: '订阅失败，请稍后重试',
        icon: 'none'
      });
      uni.$emit('refreshData', { refresh: true });
      setTimeout(() => {
        uni.navigateBack()
      }, 1000)
    },
  })
}
	// 初始化设置（参考网页3的UI规范）
	onReady(() => {
		uni.setNavigationBarTitle({
			title: '积分申报系统'
		})
	})
</script>
<style>
	.container {
		/* height: 100vh; */
		padding: 24rpx;
		background: #f8f9fa;
	}

	.container .submit-btn {
		margin-top: 40rpx;
		background: #409eff;
		color: white;
		border-radius: 48rpx;
	}

	.container {
		/* height: 100vh; */
		padding: 24rpx;
		background: #f8f9fa;
	}

	/* 新增：积分说明样式 */
	.score-info {
		margin: 30rpx 0;
		padding: 20rpx;
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.info-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 15rpx;
		padding-bottom: 10rpx;
		border-bottom: 1px solid #f0f0f0;
	}

	.info-content {
		font-size: 26rpx;
		color: #666;
	}

	.info-item {
		margin: 12rpx 0;
		line-height: 1.6;
	}

	.container .submit-btn {
		margin-top: 40rpx;
		background: #409eff;
		color: white;
		border-radius: 48rpx;
	}
</style>